package com.mokairui.basic.demo;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.nio.ByteBuffer;

/**
 * @author Mokairui
 * @Description
 * @Since 2021/6/28
 */
@Slf4j(topic = "c.BufferTest")
public class BufferTest {
    @Test
    public void test() {
        // 1.分配一个缓冲区，容量设置为10
        ByteBuffer buffer = ByteBuffer.allocate(10);
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
        System.out.println("===========================");
        // 2.put往缓冲区中添加数据
        String name = "itcast";
        buffer.put(name.getBytes());
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
        System.out.println("===========================");
        // 3.Buffer flip() 为 缓冲区的界限设置为当前位置，并将当前位置设置值为0,用于切换为读取模式
        buffer.flip();
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
        System.out.println("===========================");
        // 4.get数据的读取
        char c = (char) buffer.get();
        System.out.println(c);
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
        System.out.println("===========================");
        byte[] bytes = new byte[3];
        buffer.get(bytes);
        String msg = new String(bytes);
        System.out.println(msg);
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
        System.out.println("===========================");
        buffer.mark(); // 标记此刻位置 position = 4
        log.debug("buffer.mark()");

        byte[] bytes1 = new byte[2];
        buffer.get(bytes1);
        msg = new String(bytes1);
        System.out.println(msg);
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
        System.out.println("===========================");

        buffer.reset(); // 回到标记的位置
        if (buffer.hasRemaining()) { // 判断是否还有元素
            System.out.println(buffer.remaining()); // 获取剩下元素的个数
        }
    }

    /**
     * 1.创建一个直接内存的缓冲区
     * 数据转移比非直接内存块，但是申请比较慢，如果连接较长且数据操作量大可以使用直接内存
     */
    @Test
    public void test2() {
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(10);
        System.out.println(byteBuffer.isDirect());
    }
}
